package com.zd.lib.http.okhttp;


import com.zd.lib.App;
import com.zd.lib.utils.NetworkUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zoudong on 16/8/18.
 * 缓存 http  信息
 */
public class CacheInterceptor implements Interceptor  {


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (!NetworkUtils.isNetworkAvailable(App.getInstance())) {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        } else {
            request = request.newBuilder()
                    .cacheControl(new CacheControl.Builder()
                            .maxStale(1, TimeUnit.HOURS)
                            .build())
                    .build();
        }

        Response originalResponse = chain.proceed(request);
        if(!NetworkUtils.isNetworkAvailable(App.getInstance())){
            //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
            String cacheControl = request.cacheControl().toString();
            return originalResponse.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .removeHeader("Pragma")
                    .build();
        }else{
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=2419200")
                    .removeHeader("Pragma")
                    .build();
        }
    }


}
